import { getToken, setToken, removeToken, getTokenInfo } from '@/libs/accessToken';

const user = {
  state() {
    return {
      token: getToken(),
      userInfo: {
        username: '',
        userId: null,
        isAdmin: -1
      },
      avatar: '',
      roleIds: [] // 角色
    };
  },

  getters: {
    token: (state) => state.token,
    username: (state) => state.userInfo?.username,
    avatar: (state) => state.avatar,
    roleIds: (state) => state.roleIds,
    isAdmin: (state) => state.userInfo?.isAdmin ?? -1
  },

  mutations: {
    SET_USER_ID(state, userId) {
      state.userInfo.userId = userId;
    },
    SET_USER(state, userInfo) {
      state.userInfo = userInfo;
    },
    SET_ROLE_IDS(state, roleIds) {
      state.roleIds = roleIds;
    },
    SET_TOKEN(state, token) {
      state.token = token;
      setToken(token);
    },
    SET_AVATAR(state, avatar) {
      state.avatar = avatar;
    }
  },
  actions: {
    // 获取登录用户的信息
    async getUserInfo({ commit, state }) {
      try {
        const data = await getTokenInfo();

        const { username, userId, isAdmin, roleIds } = data;

        commit('SET_USER', {
          username,
          userId,
          isAdmin
        });
        commit('SET_ROLE_IDS', roleIds ?? []);
        // commit('SET_AVATAR', data?.avatar);

        return {
          isAdmin,
          roleIds
        };
      } catch (err) {
        console.warn('获取用户信息异常', err);
        throw err; // 重新抛出错误，这样调用者可以捕获它
      }
    },

    clearLoginInfo({ commit }) {
      commit('SET_TOKEN', '');
      commit('SET_ROLE_IDS', []);
      // commit('SET_AVATAR', '');
      commit('SET_USER', {
        username: '',
        userId: null,
        isAdmin: -1
      });
      commit('SET_USER_ID', null);
    }
  }
};

export default {
  namespaced: true,
  ...user
};
